package com.atguigu.educenter.controller;

import com.atguigu.commonutils.JwtUtils;
import com.atguigu.educenter.entity.UcenterMember;
import com.atguigu.educenter.service.UcenterMemberService;
import com.atguigu.educenter.utils.ConstantWxUtils;
import com.atguigu.educenter.utils.HttpClientUtils;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.google.gson.Gson;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

/**
 * @author: 亚当
 * @date: 2022年07月10日 11:04
 * @package: com.atguigu.educenter.controller
 * @Description: TODO
 */
@CrossOrigin
@Controller//注意这里没有配置 @RestController
@RequestMapping("/api/ucenter/wx")
public class WxApiController {

    @Autowired
    private UcenterMemberService memberService;
    //2.微信服务器回调方法
    @ApiOperation("微信服务器回调方法")
    @GetMapping("callback")
    public String callback(String code,String state){
        String jwtToken =null;
        try {
            //1.获取到两个值，state原样传递 code 类似于手机验证码，是一个随机的值
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";
            //2.获取到两个值access_token:访问凭证  openid:每个微信唯一的值
            //拼接参数
            String accessTokenUrl = String.format(baseAccessTokenUrl,
                    ConstantWxUtils.WX_OPEN_APP_ID,
                    ConstantWxUtils.WX_OPEN_APP_SECRET,
                    code);
            //使用httpClient发送请求，得到返回结果
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            System.out.println("accessTokenInfo: "+accessTokenInfo);
            Gson gson = new Gson();
            HashMap mapAccessToken = gson.fromJson(accessTokenInfo, HashMap.class);
            String access_token = (String)mapAccessToken.get("access_token");
            String openid = (String) mapAccessToken.get("openid");

            //把扫码人信息添加到数据库里面
            //先判断数据库是否存在相同openid
            UcenterMember member = memberService.getOpenId(openid);
            if (member ==null){  //member为空，表里没有相同微信数据，进行添加
                //3.拿着access_token和openid，再去请求一个固定的地址，最终可以获得微信昵称，头像等等
                //访问微信的资源服务器，获取用户信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(baseUserInfoUrl,
                        access_token,
                        openid);
                String userInfo = HttpClientUtils.get(userInfoUrl);
                System.out.println("userInfo : "+userInfo);
                HashMap userInfoMap = gson.fromJson(userInfo, HashMap.class);
                System.out.println("userInfoMap : "+userInfoMap);
                String nickname = (String) userInfoMap.get("nickname");
                String headimgurl = (String) userInfoMap.get("headimgurl");
                member.setNickname(nickname);
                member.setAvatar(headimgurl);
                member.setOpenid(openid);
                memberService.save(member);
            }
            //使用jwt根据member对象生成token字符串

            //最后，返回首页面，通过路径传递token字符串
            jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());
        }catch (Exception e){
            new GuliException(20001,"登录失败");
        }
        return "redirect:http://localhost:3000?token="+jwtToken;
    }

    //生成微信扫描的二维码
    @GetMapping("login")
    public String getWxCode(){

        //固定的地址后面拼接参数
        //String url="https://open.weixin.qq.com/connect/qrconnect";
        // 微信开放平台授权baseUrl  %s相当于？占位符
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";
        //对redirect_uri进行URLEncode编码
        String redirectUrl = ConstantWxUtils.WX_OPEN_REDIRECT_URL;
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "UTF-8"); //url编码
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //设置%s的值
        String url = String.format(baseUrl,
                ConstantWxUtils.WX_OPEN_APP_ID, //wx.open.app_id=wxed9954c01bb89b47
                redirectUrl, //wx.open.redirect_url=http://localhost:8160/api/ucenter/wx/callback
                "atguigu");
        //请求微信地址
        return "redirect:"+url;
    }
}
